
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#include "rp2040.h"
#include "structs/uart.h"
#include "drvs/clocks.h"
#include "drvs/resets.h"
#include "drvs/gpio.h"
#include "drvs/i2c.h"

/**/
#include "pico.h"
#include "pico/multicore.h"

#include "umsg.h"
#include "ttusb_comn.h"
#include "ttusb.h"



void tttdelay( uint32_t cnt )
{
	uint32_t  i;

	for (i=0; i<cnt; i++ ) {
		__NOP();
	}
}



static uint32_t ttt_ticks = 0;

void  SysTick_Handler( void )
{
	ttt_ticks += 1;

#if 0
	if ( ttt_ticks & 0x2 )  {
		gpio_put( 25, true );
	} else {
		gpio_put( 25, false );
	}
#endif

	return;
}


void HardFault_exception( void )
{
	printf( "hard fault ...\n" );
	while ( 1 )  {
		__asm volatile ( "nop" );
		__asm volatile ( "wfi" );
	}
}


extern void core1_main( void );
extern void core0_proc_msg( umsg_t * pmsg );


int main( void )
{
	int iret;
	uint32_t  tary[4];

	/* pio init, interface for HAD, SWD */
	//iret = had_mod_init( 10, 8, 10 );
	//printf( "had, pio, init ret = %d\n", iret );

	/**/
	iret = umsg_init(64);
	printf( "umsg pool, init ret = %d\n", iret );

	/* usb auto */
	ttusb_desc_init();
	ttusb_desc_device_vid_pid( 0x2E8A, 0x1014 );
	ttusb_desc_device_str_manu( "TTusb" );
	ttusb_desc_device_str_prod( "swiss" );
	ttusb_desc_config_power( 0x64 );
	ttusb_desc_interface_add_inp( umsg_inp_cbk );
	ttusb_desc_interface_add_outp( umsg_outp_cbk );
	ttusb_init();

	/* core-1 */
	multicore_launch_core1_raw( core1_main, (uint32_t *)(uintptr_t)0x20042000, 0x10000200 );
	NVIC_EnableIRQ( SIO_IRQ_PROC0_IRQn );
	
	/**/
	SysTick_Config( 9000000 );
	printf("hello...\n");

	/**/
	while ( 1 )  {

		iret = symsg_recv_from_system( 4, tary );
		if ( iret != 0 ) {
			__WFI();
			continue;
		}
		
		if ( tary[0] == SYS_UMSG ) {
			
			int mlen;
			umsg_t * pmsg;


			/**/
			pmsg = (umsg_t *)(uintptr_t)tary[1];
			

			/* check length */
			if ( pmsg->mlen <= 0 ) {
				umsg_free( pmsg );
				continue;
			}

			/**/
			pmsg->type = pmsg->data[0];
			pmsg->type = pmsg->type & 0x3F;
			umsg_reset_ofs( pmsg );
			core0_proc_msg( pmsg );
			continue;
		}

	}

	return 0;
}

